/*
 * 文件名               :  DataReaderThread.java
 * 用途                    :  负责读取流中的对象
 * 最后修改日期:  $LastChangedDate: 2009-10-17 03:54:49 +0000 (Sat, 17 Oct 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wendal.java.preproxy.bean.ByteArrayMessageBean;
import com.wendal.java.preproxy.bean.NoticeMessageBean;
import com.wendal.java.preproxy.bean.TerminateMessageBean;
import com.wendal.java.preproxy.bridge.ByteArrayHandler;
import com.wendal.java.preproxy.server.SocketHandlerFinder;

public class DataReaderThread extends Thread {

	private Log log = LogFactory.getLog(getClass());

	private InputStream is;


	private SocketHandlerFinder outputFinder;
	
	private ByteArrayHandler handler;
	
	private ObjectInputStream ois;

	public DataReaderThread(InputStream is, SocketHandlerFinder outputFinder,ByteArrayHandler handler)
			throws IOException {
		this.is = is;
		this.outputFinder = outputFinder;
		this.handler = handler;
	}
	
//	public DataReaderThread(Socket socket, SocketHandlerFinder outputFinder,ByteArrayHandler handler,ObjectInputStream ois) throws IOException {
//		this.socket = socket;
//		this.outputFinder = outputFinder;
//		this.handler = handler;
//		this.ois = ois;
//	}

	@Override
	public void run() {
		try {
			if(ois == null )
				ois = new ObjectInputStream(is);
		} catch (IOException e1) {
			e1.printStackTrace();
//			Toolkit.close(socket);
			return;
		}
		while (true) {
			try {
				Object object = ois.readObject();
//				log.info("接收到一个对象 " + object);
				if (object instanceof NoticeMessageBean) {
					log.info(((NoticeMessageBean) object).getData());
				} else if (object instanceof ByteArrayMessageBean) {
					ByteArrayMessageBean bean = (ByteArrayMessageBean) object;
					SocketHandler socketHandler = outputFinder
							.get(bean.getFrom_id());
					if(socketHandler == null ){
						handler.handle(bean.getFrom_id(), outputFinder);
						socketHandler = outputFinder.get(bean.getFrom_id());
					}
					if (socketHandler != null) {
						socketHandler.writeData(bean.getData());
					} 
				}else if(object instanceof TerminateMessageBean){
					TerminateMessageBean terminateMessageBean = (TerminateMessageBean)object;
					if(terminateMessageBean.getTerminateId() != null){
						SocketHandler socketHandler = outputFinder.remove(terminateMessageBean.getTerminateId());
						if(socketHandler != null){
							socketHandler.sendTerminateSign();
						}
					}
				}else{
					log.debug("接收到一条未知类型的信息,类型为 "+object.getClass().getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
				break;
			}
		}
	}
}
